const { promisify } = require('util')
const jwt = require('jsonwebtoken')
const sign = promisify(jwt.sign)
const verify = promisify(jwt.verify)

//创建token
module.exports.createToken = async (user)=>{
    const token = await sign(user,'dhjyyds',{expiresIn:'1d'})
   
    return token
}

//验证token
module.exports.verifyToken =  (required=true)=>{
    return async (req,res,next)=>{
        const token = req.headers.authorization?req.headers.authorization.split(' ')[1]:null
        if(token) {
            try {
                const user = await verify(token,'dhjyyds')
                req.user = user
                next()
            } catch (error) {
                return res.status(401).json({
                    code:401,
                    data:null,
                    message:'登录已过期，请重新登录'
                })
            }
        }else if(required) {
            return res.status(401).json({
                code:401,
                data:null,
                message:'未登录，请登录账号'
            })
        }else {
            next()
        }
    }
}
